#    Copyright (C) 2019 Mason Hock <mason@masonhock.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#

import os
import random
import requests

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GLib

from .channels import Channel
from .library import Library
from .playback import Player
from .search import Search


class App:
    def __init__(self):
        self.builder = Gtk.Builder()
        self.builder.add_from_file(
            os.path.dirname(__file__) + "/data/libricia-music.glade"
        )
        self.builder.connect_signals(self)

        self.window = self.builder.get_object("window")
        self.searchpopup = self.builder.get_object("searchpopup")
        self.searchresults = self.builder.get_object("searchresults")
        self.playpause_button = self.builder.get_object("playpause")
        self.playback_bar = self.builder.get_object("playbackbar")
        self.timestamp = self.builder.get_object("timestamp")
        self.playliststore = Gtk.ListStore()
        self.libraryliststore = self.builder.get_object("libraryliststore")
        self.savebutton = self.builder.get_object("savebutton")

        self.playback_bar_is_pressed = False
        self.player = Player()
        GLib.timeout_add(250, self.update_gui)
        self.search = Search()

        self.tracks_saved = Library()
        self.tracks_saved.load()
        self.tracks_playing = Library()
        self.tracks_displayed = Library()
        self.tracks_displayed.update(self.tracks_saved)
        self.tracks_displayed.populate_liststore(self.libraryliststore)

        self.window.show_all()

    def update_gui(self):
        now_playing = self.player.get_now_playing()

        if (
            now_playing is not None
            and now_playing["track_id"] not in self.tracks_playing
        ):
            self.tracks_playing = Library()
            self.tracks_playing.add_track(now_playing)
            self.tracks_displayed = Library()
            self.tracks_displayed.update(self.tracks_saved)
            self.tracks_displayed.update(self.tracks_playing)
            self.libraryliststore.clear()
            self.tracks_displayed.populate_liststore(self.libraryliststore)

        self.player.update_gui(
            self.libraryliststore,
            self.playback_bar,
            self.playback_bar_is_pressed,
            self.timestamp,
            self.playpause_button,
        )
        if now_playing is None or now_playing["track_id"] not in self.tracks_saved:
            self.savebutton.set_active(False)
        else:
            self.savebutton.set_active(True)
        return True

    def on_search_clicked(self, button):
        self.searchpopup.show_all()
        self.searchpopup.popup()

    def on_search_changed(self, searchentry):
        self.searchresults.clear()
        self.search.search_artists(searchentry.get_text())
        for result in self.search.results:
            self.searchresults.append((result["name"],))

    def on_search_activate(self, searchentry):
        if len(self.search.results) > 0:
            self.searchpopup.popdown()
            self.player.channel = Channel(self.search.results[0])
            self.player.request_track()
            self.player.start_track(0)

    def on_search_row_activated(self, treeview, path, column):
        self.searchpopup.popdown()
        channel = Channel(self.search.results[path.get_indices()[0]])
        self.player.request_track()
        self.player.start_track(0)

    def on_play_pause(self, button):
        if self.player.is_playing:
            self.player.pause()
        else:
            self.player.play()
        self.update_gui()

    def on_next(self, button):
        self.player.next()
        self.update_gui()

    def on_previous(self, button):
        self.player.previous()
        self.update_gui()

    def on_window_key_press(self, window, event):
        keyname = Gdk.keyval_name(event.keyval)
        if Gdk.ModifierType.CONTROL_MASK:
            if keyname == "q":
                Gtk.main_quit()

    def on_volume_changed(self, button, value):
        self.player.set_volume(value)

    def on_playback_bar_change(self, scale, scroll, value):
        self.player.set_position(value, percent=True)

    def on_playback_bar_press(self, scale, event):
        self.playback_bar_is_pressed = True

    def on_playback_bar_release(self, scale, event):
        self.playback_bar_is_pressed = False
        self.player.update_position()

    def on_playback_bar_scroll(self, widget, value):
        return True

    def on_track_activated(self, treeview, path, column):
        treeiter = self.libraryliststore.get_iter(path)
        track = self.tracks_displayed.get_track(
            self.libraryliststore.get_value(treeiter, 0)
        )
        if track is not None:
            self.player.queue_track(track)
            self.player.start_track(len(self.player.queue) - 1)
        self.update_gui()

    def on_save_button_toggled(self, button):
        now_playing = self.player.get_now_playing()
        if now_playing is None:
            button.set_active(False)
        elif button.get_active():
            self.tracks_saved.add_track(now_playing)
        else:
            self.tracks_saved.remove_track(now_playing["track_id"])
        self.tracks_saved.save()

    def on_window_destroy(self, widget):
        Gtk.main_quit()


def main():
    App()
    Gtk.main()
